package com.css.zfzx.sjcj.modules.hddcDrillFaultPoint.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.constants.PlatformConstants;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.PlatformDateUtils;
import com.css.bpm.platform.utils.PlatformObjectUtils;
import com.css.bpm.platform.utils.PlatformPageUtils;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.bpm.platform.utils.UUIDGenerator;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcDrillFaultPoint.repository.HddcDrillfaultpointNativeRepository;
import com.css.zfzx.sjcj.modules.hddcDrillFaultPoint.repository.HddcDrillfaultpointRepository;
import com.css.zfzx.sjcj.modules.hddcDrillFaultPoint.repository.entity.HddcDrillfaultpointEntity;
import com.css.zfzx.sjcj.modules.hddcDrillFaultPoint.service.HddcDrillfaultpointService;
import com.css.zfzx.sjcj.modules.hddcDrillFaultPoint.viewobjects.HddcDrillfaultpointPageVO;
import com.css.zfzx.sjcj.modules.hddcDrillFaultPoint.viewobjects.HddcDrillfaultpointQueryParams;
import com.css.zfzx.sjcj.modules.hddcDrillFaultPoint.viewobjects.HddcDrillfaultpointVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author zyb
 * @date 2020-11-30
 */
@Service
public class HddcDrillfaultpointServiceImpl implements HddcDrillfaultpointService {

    private final HddcDrillfaultpointRepository hddcDrillfaultpointRepository;
    private final HddcDrillfaultpointNativeRepository hddcDrillfaultpointNativeRepository;
    private final AcrossFaultDrillingPointExcelVerifyHandler acrossFaultDrillingPointExcelVerifyHandler;

    @Autowired
    public HddcDrillfaultpointServiceImpl(HddcDrillfaultpointRepository hddcDrillfaultpointRepository,
                                          HddcDrillfaultpointNativeRepository hddcDrillfaultpointNativeRepository,
                                          AcrossFaultDrillingPointExcelVerifyHandler acrossFaultDrillingPointExcelVerifyHandler) {
        this.hddcDrillfaultpointRepository = hddcDrillfaultpointRepository;
        this.hddcDrillfaultpointNativeRepository = hddcDrillfaultpointNativeRepository;
        this.acrossFaultDrillingPointExcelVerifyHandler = acrossFaultDrillingPointExcelVerifyHandler;
    }

    @Override
    public JSONObject queryHddcDrillfaultpoints(HddcDrillfaultpointQueryParams queryParams, int curPage, int pageSize, String sort, String order) {
        Page<HddcDrillfaultpointPageVO> hddcDrillfaultpointPage = this.hddcDrillfaultpointNativeRepository.queryHddcDrillfaultpoints(queryParams, curPage, pageSize, sort, order);
        return PlatformPageUtils.formatPageData(hddcDrillfaultpointPage);
    }


    @Override
    public HddcDrillfaultpointEntity getHddcDrillfaultpoint(String id) {
        return this.hddcDrillfaultpointRepository.findById(id).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcDrillfaultpointEntity saveHddcDrillfaultpoint(HddcDrillfaultpointEntity hddcDrillfaultpoint) {
        String uuid = UUIDGenerator.getUUID();
        hddcDrillfaultpoint.setUuid(uuid);
        hddcDrillfaultpoint.setCreateUser(PlatformSessionUtils.getUserId());
        Timestamp now = PlatformDateUtils.getCurrentTimestamp();
        hddcDrillfaultpoint.setCreateTime(now);
        hddcDrillfaultpoint.setUpdateTime(now);
        hddcDrillfaultpoint.setIsValid(PlatformConstants.Y);
        hddcDrillfaultpoint.setQualityinspectionStatus(PlatformConstants.N);
        hddcDrillfaultpoint.setExtends10(PlatformConstants.Y);
        this.hddcDrillfaultpointRepository.save(hddcDrillfaultpoint);
        return hddcDrillfaultpoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcDrillfaultpointEntity updateHddcDrillfaultpoint(HddcDrillfaultpointEntity hddcDrillfaultpoint) {
        HddcDrillfaultpointEntity entity = hddcDrillfaultpointRepository.findById(hddcDrillfaultpoint.getUuid()).get();
        UpdateUtil.copyNullProperties(entity, hddcDrillfaultpoint);
        hddcDrillfaultpoint.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcDrillfaultpoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcDrillfaultpointRepository.save(hddcDrillfaultpoint);
        return hddcDrillfaultpoint;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcDrillfaultpoints(List<String> ids) {
        List<HddcDrillfaultpointEntity> hddcDrillfaultpointList = this.hddcDrillfaultpointRepository.findAllById(ids);
        if (!PlatformObjectUtils.isEmpty(hddcDrillfaultpointList) && hddcDrillfaultpointList.size() > 0) {
            for (HddcDrillfaultpointEntity hddcDrillfaultpoint : hddcDrillfaultpointList) {
                hddcDrillfaultpoint.setIsValid(PlatformConstants.N);
                hddcDrillfaultpoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcDrillfaultpoint.setUpdateTime(new Date());
                this.hddcDrillfaultpointRepository.save(hddcDrillfaultpoint);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        return PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
    }

    @Override
    public void exportFile(HddcDrillfaultpointQueryParams queryParams, HttpServletResponse response) {
        List<HddcDrillfaultpointEntity> yhDisasterEntities = hddcDrillfaultpointNativeRepository.exportYhDisasters(queryParams);
        List<HddcDrillfaultpointVO> list = new ArrayList<>();
        for (HddcDrillfaultpointEntity entity : yhDisasterEntities) {
            HddcDrillfaultpointVO yhDisasterVO = new HddcDrillfaultpointVO();
            BeanUtils.copyProperties(entity, yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "跨断层钻探断点-点", "跨断层钻探断点-点",
                HddcDrillfaultpointVO.class, "跨断层钻探断点-点.xls", response);
    }

    @Override
    public String importExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            params.setVerifyHandler(acrossFaultDrillingPointExcelVerifyHandler);
            // 获取到Excel数据
            ExcelImportResult<HddcDrillfaultpointVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcDrillfaultpointVO.class, params);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                for (HddcDrillfaultpointVO yhDisasterVO : result.getFailList()) {
                    returnMsg.append("第").append(yhDisasterVO.getRowNum()).append("行").append(yhDisasterVO.getErrorMsg()).append("<br/>");
                }
                if (returnMsg.length() > 0)
                    return returnMsg.toString();
            }
            List<HddcDrillfaultpointVO> list = result.getList();
            //保存
            saveDisasterList(list);
            return returnMsg.append("成功导入").append(result.getList().size()).toString();
        } catch (Exception e) {
            return "导入失败，请检查数据正确性";
        }
    }

    /**
     * 批量存入库表并且返回错误数量
     */
    public void saveDisasterList(List<HddcDrillfaultpointVO> list) {
        for (HddcDrillfaultpointVO hddcDrillfaultpointVO : list) {
            HddcDrillfaultpointEntity yhDisasterEntity = new HddcDrillfaultpointEntity();
            BeanUtils.copyProperties(hddcDrillfaultpointVO, yhDisasterEntity);
            saveHddcDrillfaultpoint(yhDisasterEntity);
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcDrillfaultpointEntity> hddcDrillfaultpointList = this.hddcDrillfaultpointRepository.queryHddcDrillfaultpointsByProjectId(projectIds);
        if (!PlatformObjectUtils.isEmpty(hddcDrillfaultpointList) && hddcDrillfaultpointList.size() > 0) {
            for (HddcDrillfaultpointEntity hddcDrillfaultpoint : hddcDrillfaultpointList) {
                hddcDrillfaultpoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcDrillfaultpoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcDrillfaultpoint.setIsValid(PlatformConstants.N);
                this.hddcDrillfaultpointRepository.save(hddcDrillfaultpoint);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     */
    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcDrillfaultpointEntity> hddcDrillfaultpointList = this.hddcDrillfaultpointRepository.queryHddcDrillfaultpointsByTaskId(taskIds);
        if (!PlatformObjectUtils.isEmpty(hddcDrillfaultpointList) && hddcDrillfaultpointList.size() > 0) {
            for (HddcDrillfaultpointEntity hddcDrillfaultpoint : hddcDrillfaultpointList) {
                hddcDrillfaultpoint.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcDrillfaultpoint.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcDrillfaultpoint.setIsValid(PlatformConstants.N);
                this.hddcDrillfaultpointRepository.save(hddcDrillfaultpoint);
            }
        }
    }

}
